<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=], initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    Object.prototype.aaa = "11"
    var person1 = {
      name: 'mashaodong',
      age: 12,
      sex: '男',
      obj: {
        name: 'dahuang'
      },
      arr: [1, 2, 3]
    }
    var person2 = deepClone(person1)
    person2.name = 'xiaohong';
    person2.jj = 20;
    person2.obj.name = 'sandezi'
    person2.arr.push(4)
    var person3 = { ...person1 } // 相当于结构赋值，只是展开了一层
    person3.name = 'xiaosan';
    person3.obj.name = 'person3'

    var person4 = JSON.parse(JSON.stringify(person1))// 深拷贝
    person4.name = 'person4';
    person4.obj.name = 'person4'


    // for (let key in person1) {
    //   console.log(person1[key])
    // }

    console.log(person1, person2, person3, person4)  // 浅拷贝值拷贝了一层，如果有深层次的嵌套就没用了
    // 浅拷贝
    // function clone(origin, target) {
    //   var tar = target || {};
    //   for (var key in origin) {
    //     if (origin.hasOwnProperty(key)) {
    //       tar[key] = origin[key]
    //     }
    //   }
    //   return tar;
    // }

    // 深拷贝
    function deepClone(origin, target) {
      let toStr = Object.prototype.toString;
      let strObj = '[object Array]';
      let tar = target || {};
      for (let key in origin) {
        if (origin.hasOwnProperty(key)) {
          if (typeof (origin[key]) === 'object' && origin[key] != null) {
            toStr.call(origin[key]) === strObj ? tar[key] = []
              : tar[key] = {};
            deepClone(origin[key], tar[key])
          } else {
            tar[key] = origin[key]
          }
        }
      }
      return tar
    }



    // 平时用的

  </script>
</body>

</html>